#include "mystdio.h"
FILE * myfopen ( const char * filename, const char * mode )
{
    int oflags = 0, omode;
    int oprot=0666;
    switch (*mode)
    {
    case 'r':
      omode = O_RDONLY;
      break;
    case 'w':
      omode = O_WRONLY;
      oflags = O_CREAT|O_TRUNC;
      break;
    case 'a':
      omode = O_WRONLY;
      oflags = O_CREAT|O_APPEND;
      break;
    default:
      return NULL;
    }
    int fd=open(filename, omode|oflags, oprot);
    if (fd==-1)
      return NULL;
    FILE * fp = malloc(sizeof(FILE));
    if (fp==NULL)
    {
      return NULL;
    }
    fp->_fileno = fd;
    fp->buf_pos = 0;
    fp->flush_style = FIUSH_ALL;
    return fp;
}
size_t myfwrite ( const void * ptr, size_t size, size_t count, FILE * stream )
{
  memcpy(stream->buffer+stream->buf_pos, (char*)ptr, count*size);
  size_t start=stream->buf_pos;
  size_t len=count*size;
  stream->buf_pos += count*size;
  if (stream->flush_style&FIUSH_NOW)
  {
    write(stream->_fileno, stream->buffer,stream->buf_pos);//调用write立刻刷新
    stream->buf_pos=0;
  }
  else if (stream->flush_style&FIUSH_LINE)
  {
    if (((char*)stream->buffer)[stream->buf_pos-1]=='\n')
    {
      write(stream->_fileno, stream->buffer+start, len);
      stream->buf_pos=0;
    }
  }
  else//stream->flush_style&FIUSH_ALL
  {
      write(stream->_fileno, stream->buffer,stream->buf_pos);
      stream->buf_pos=0;
  }
  return len;
}
int myfclose ( FILE * stream )
{
  if (stream->_fileno==-1)
    return -1;
  if (stream->buf_pos>0)
  {
    write(stream->_fileno, stream->buffer,stream->buf_pos);
    stream->buf_pos=0;
  }
  close(stream->_fileno);
  free(stream);
  return 0;
}